extends CharacterBody2D

# INFO: Temporary
@export var init_attributes: Array[Attribute]

# INFO: Temporary
@export var init_abilities: Array[GameplayAbilityAsset]

# INFO: Temporary
@export var posion_effect_asset: GameplayEffectAsset

# INFO: Temporary
@export var health_up_effect_asset: GameplayEffectAsset

var attribute_manager: AttributeManager

var ability_manager: GameplayAbilityManager

var effect_manager: GameplayEffectManager

var tag_manager: Tag

var face_direction: int

var state_machine: StateMachine

var input_handler: InputHandler

@onready var animator: AnimatedSprite2D = %Animator

@onready var weapon_manager: Node2D = $WeaponManager


func flip() -> void:
	scale.x = -scale.x
	face_direction = -face_direction


func _ready() -> void:
	face_direction = 1
	
	tag_manager = Tag.new("")
	
	attribute_manager = AttributeManager.new()
	attribute_manager.add_attributes(init_attributes)
	attribute_manager.get_attribute("health").max_value = attribute_manager.get_attribute("max_health").current_value
	attribute_manager.get_attribute("max_health").current_value_changed.connect(
		func(_old: float, new: float):
			attribute_manager.get_attribute("health").max_value = new
	)
	
	effect_manager = GameplayEffectManager.new(self)
	
	ability_manager = GameplayAbilityManager.new(self)
	ability_manager.grant_abilities(init_abilities)
	
	input_handler = InputHandler.new()
	
	state_machine = PlayerStateMachine.new(self)
	state_machine.on_setup()
	
	weapon_manager.attach_weapon()


func _process(delta: float) -> void:
	input_handler.on_update(delta)
	ability_manager.on_update(delta)
	effect_manager.on_update(delta)
	state_machine.on_update(delta)
	weapon_manager.on_update(delta)
	move_and_slide()
	
	#print("tags: ", tag_manager.get_leaf_tag_paths())
	#print("leaf state path: ", state_machine.get_leaf_state_path())

	# print("max_health: ", attribute_manager.get_attribute("max_health").current_value)
	# print("health: ", attribute_manager.get_attribute("health").current_value)
	
	if input_handler.is_action_just_pressed("jump"):
		ability_manager.try_apply_ability_by_name("jump", self)

	if input_handler.is_action_just_pressed("test_posion"):
		effect_manager.attach_effect(posion_effect_asset, self)

	if input_handler.is_action_just_pressed("test_health_up_on"):
		effect_manager.attach_effect(health_up_effect_asset, self)

	if input_handler.is_action_just_pressed("test_health_up_off"):
		effect_manager.detach_effect(health_up_effect_asset, self)

	if input_handler.is_action_just_pressed("test_health_to_max"):
		attribute_manager.get_attribute("health").to_max()
